import json

from modules.utils.log_util import LOGGER
from flask_restx import Resource, namespace

from modules.utils.message import success, error
from modules.utils.redis_cache import CACHE

view_namespace = namespace.Namespace("service", description="数据服务接口")


@view_namespace.route("/topic/baidu")
class BaiduTrendingTopic(Resource):
    def post(self):
        data = CACHE.get("baidu_data")
        if data:
            data.decode("utf-8")
            data = json.loads(data)
            return success(data)
        return error("获取数据失败")


@view_namespace.route("/topic/360")
class Q360TrendingTopic(Resource):
    def post(self):
        data = CACHE.get("q360_data")
        if data:
            data.decode("utf-8")
            data = json.loads(data)
            return success(data)
        return error("获取数据失败")


@view_namespace.route("/topic/weibo")
class WeiboTrendingTopic(Resource):
    def post(self):
        data = CACHE.get("weibo_data")
        if data:
            data.decode("utf-8")
            data = json.loads(data)
            return success(data)
        return error("获取数据失败")


@view_namespace.route("/task/start")
class WeiboTrendingTopic(Resource):
    def post(self):
        CACHE.delete("taskStop")
        LOGGER.info("抓取任务已恢复")
        return success("抓取任务已恢复")


@view_namespace.route("/task/stop")
class WeiboTrendingTopic(Resource):
    def post(self):
        CACHE.set("taskStop", "stop")
        LOGGER.info("抓取任务已经暂停")
        return success("任务暂停")
